package problema049;

import java.util.Iterator;
import java.util.LinkedList;

public class PrimePermutations {
	
	static boolean[] isPrime;
	static boolean[] numeros = new boolean[10];
	
	
	public static void main(String[] args){
		serie();
	}
	
	public static void serie(){
		sieveOfEratosthenes(10000);
		LinkedList<Integer> res = new LinkedList<Integer>();
		int cand = 0, act = 0;
		boolean[] num = new boolean[10];
		for(int i = 1000; i < isPrime.length; i++){
			if(isPrime[i] && (res = existePermutacionPrimo(i)).size() != 0){
				numeros = new boolean[10];
				pasarArreglo(i, numeros);
				Iterator<Integer> it = res.iterator();
				while(it.hasNext()){
					act = it.next();
					cand = Math.abs(act - i) / 2;
					if(i < act){
						cand += i;
					}else{
						cand += act;
					}
					if(!isPrime[cand]) continue;
					num = new boolean[10];
					pasarArreglo(cand, num);
					if(!sonIguales(num)) continue;
					System.out.println(i + " " + cand + " " + act);
				}
			}
		}
	}
	
	public static LinkedList<Integer> existePermutacionPrimo(int n){
		LinkedList<Integer> res = new LinkedList<Integer>();
		boolean[] nn = new boolean[10];
		pasarArreglo(n, nn);
		for(int i = 1000; i < isPrime.length; i++){
			if(isPrime[i] && i != n){
				numeros = new boolean[10];
				pasarArreglo(i, numeros);
				if(sonIguales(nn)){
					res.add(i);
				}
			}
		}
		return res;
	}
	
	public static void pasarArreglo(int i, boolean[] a){
		while(i > 0){
			a[i%10] = true;
			i = i / 10;
		}
	}
	
	public static boolean sonIguales(boolean[] numero){
		for(int i = 0; i < numero.length; i++){
			if(numero[i] != numeros[i]) return false;
		}
		return true;
	}
	
	public static void sieveOfEratosthenes(int n){
		isPrime = new boolean[n + 1];
	     for (int i = 2; i <= n; i++) {
	    	 isPrime[i] = true;
	     }
	     for (int i = 2; i*i <= n; i++) {
	         if (isPrime[i]) {
	             for (int j = i; i*j <= n; j++) {
	            	 isPrime[i*j] = false;
	             }
	         }
	     }
	 }
	

}
